import { MciButton } from '@/components/base';
import { useFormMode } from '@/components/base/Form/mode';
import { PropType } from 'vue';
import './index.scss';

export const RowIndex = defineComponent({
  props: {
    index: {
      type: Number,
      default: 0
    },
    list: {
      type: Array as PropType<any[]>,
      default: () => []
    },
    hasNum: {
      type: Boolean,
      default: true
    },
    noAssignment: {
      type: Boolean,
      default: false
    },
    hasCopy: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:list', 'delete', 'copy'],
  setup(props, { slots, emit }) {
    const deleteRow = () => {
      const list = props.list.concat();
      list.splice(props.index, 1);
      emit('update:list', list);
      emit('delete', props.index);
    };
    const copyRow = () => {
      const list = props.list.concat();
      // const list2 = props.list.concat();
      try {
        const targetSTR = JSON.stringify(list[props.index]);
        const target = JSON.parse(targetSTR);
        list.splice(props.index, 0, { ...target });
      } catch (error) {
        console.log(error);
      }

      emit('update:list', list);
      emit('copy', props.index);
    };
    const formMode = useFormMode();

    return () => {
      return (
        <div class="flex w-full row-index relative">
          {props.hasNum ? (
            // <div class="row-index-num text-gray-50 w-20 h-20 mr-8 mt-10 leading-[20px] text-center bg-green-600 rounded-[50%]">
            //   {props.index + 1}
            // </div>
            <MciButton circle={true} type='success' class={'mr-8 mt-8'}>{props.index + 1}</MciButton>
          ) : null}
          <div class="flex-1 row-index-content pr-30">{slots.default?.()}</div>
          {!props.noAssignment && formMode?.mode === 'edit' && (
            <>
              <MciButton
                onClick={deleteRow}
                icon={'mci-icon-delete'}
                link={true}
                type="danger"
                plain={true}
                class="row-index-remove-btn !h-32 cursor-pointer"
              />
              {props.hasCopy && (
                <MciButton
                  class=""
                  onClick={copyRow}
                  icon={'mci-icon-file-copy'}
                  link={true}
                  type="danger"
                  plain={true}
                  class="row-index-remove-btn !h-32 cursor-pointer"
                />
              )}
            </>
          )}
        </div>
      );
    };
  }
});
